<template>
    <Layout>
        <Form ref="form1" :model="form1" :label-width="120">
            <Row v-show="!switchFlag" class="query-form" style="padding-top: 15px">
                <Col span="8">
                    <FormItem label="任务名称：">
                        <Input type="text" v-model="form1.taskName"/>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="检查日期：">
                        <DatePicker type="daterange" v-model="form1.checkTime" style="width: 100%;"></DatePicker>
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query()">查询</Button>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form" style="padding-top: 10px">
                <Col span="8">
                    <FormItem label="任务名称：">
                        <Input type="text" v-model="form1.taskName"/>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="检查日期：">
                        <DatePicker type="daterange" v-model="form1.checkTime"  style="width: 100%;"></DatePicker>
                    </FormItem>
                </Col>
                <Col span="8">
                    <FormItem label="任务状态：">
                        <Select v-model="form1.checkStatus">
                            <Option value="1">未执行</Option>
                            <Option value="2">执行中</Option>
                            <Option value="3">已执行</Option>
                        </Select>
                    </FormItem>
                </Col>
            </Row>
            <Row v-show="switchFlag" class="query-form">
                <Col span="8" offset="16">
                    <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query()">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" :loading="buttonLoading" icon="md-checkmark"
                            @click="toSubmit">提交
                    </Button>
                </Col>
            </Row>
        </Form>

        <Table ref='table' :loading="loading" size="small" :height="tableHeight" class="table" no-data-text="没有查询到相关数据!"
               @on-selection-change='getSelectRows'
               highlight-row stripe border :columns="columns1" width="100%" :data="dataTable">
        </Table>

        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
                      @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
                      show-total show-sizer show-elevator/>
            </Col>
        </Row>


            <CheckWithModel @closeModel="closeModel" @query="query" ref="hasModelModal" :editable="editable"
                            :hasModel="hasModel" :mainTaskId="mainTaskId"></CheckWithModel>

            <CheckWithoutModel @closeModel="closeModel" @query="query" ref="noModelModal" :editable="editable"
                               :noModel="noModel" :mainTaskId="mainTaskId"></CheckWithoutModel>

        <Modal :transfer=false v-model="model2" :width=500 title="责任人选择" @on-cancel="model2=false,mainInstanceId=null,checkedOrg=null">
            <Form ref="dutyUserSelect" :rules="ruleCustom" :label-width="120">
                <Row class="query-form">
                    <Col span="23">
                        <FormItem label="责任人：" prop="dutyUser">
                            <Select
                                    ref="select"
                                    placeholder="请输入关键字查询"
                                    v-model="dutyUser"
                                    filterable
                                    :remote-method="remoteMethod1"
                                    :loading="loading1">
                                <Option v-for="(option, index) in options1" :value="option.userId" :label="option.userName" :key="option.userId">
                                    <span>{{option.userName}}</span>
                                    <span style="float:right;color:#ccc">{{option.orgInfo.orgName}}</span>
                                </Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <div slot="footer">
                <Button class='ivu-btn-save' :loading="buttonLoading" @click="submit('dutyUserSelect')">确定</Button>
                <Button class='ivu-btn-cancel' @click="model2=false,mainInstanceId=null,checkedOrg=null">取消</Button>
            </div>
        </Modal>
    </layout>
</template>

<script>
    import {Api} from '../../../../api/index.js'
    import {sessionStorage} from '../../../../common/cacheUtils.js';
    import CheckWithModel from "./checkWithModel";
    import CheckWithoutModel from "./checkWithoutModel";
    import DatePickerPanel from "view-design/src/components/date-picker/panel/Date/date";

    export default {
        components: {
            DatePickerPanel,
            CheckWithModel,
            CheckWithoutModel
        },
        data() {
            return {
                mainTaskId: '',
                editable: false,
                switchFlag: false,
                defaultList: [],
                imgName: '',
                visible: false,
                uploadList: [],
                upUrl: Api.uploadPTWFiles,
                viewUrl: Api.downloadPTWSchemeFile,
                files: [],
                pictureModal: false,
                form1: {
                    checkTime:['','']
                },
                dataForm: {},
                //分页参数
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1,
                },
                selectRows: [],
                columns1: [
                    {
                        title: "序号",
                        minWidth: 80,
                        align: "center",
                        fixed: 'left',
                        type: 'selection',
                        /*render: (h, params) => {
                            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
                        }*/
                    },
                    {
                        minWidth: 220,
                        title: '任务名称',
                        key: 'taskName',
                        align: 'center'
                    },
                    {
                        minWidth: 100,
                        title: '检查日期',
                        key: 'taskDate',
                        align: 'center'
                    },
                    {
                        minWidth: 130,
                        title: '检查单位',
                        key: 'execOrgName',
                        align: 'center'
                    },
                    {
                        minWidth: 150,
                        title: '受检单位',
                        key: 'checkedOrgName',
                        align: 'center'
                    },
                    {
                        minWidth: 90,
                        title: '检查人',
                        key: 'checkedUserName',
                        align: 'center'
                    },
                   /* {
                        minWidth: 120,
                        title: '检查类型',
                        align: 'center',
                        key: 'checkType',
                        render: (h, params) => {
                            if (params.row.checkType == '0') {
                                return h('span', {}, '日常检查')
                            } else if (params.row.checkType == '1') {
                                return h('span', {}, '监督检查')
                            } else if (params.row.checkType == '2') {
                                return h('span', {}, '体系审核')
                            }
                        }
                    },*/
                    {
                        minWidth: 100,
                        title: '检查级别',
                        key: 'checkLevel',
                        align: 'center',
                        render: (h, params) => {
                            if (params.row.checkLevel == '0') {
                                return h('span', {}, '公司级')
                            } else if (params.row.checkLevel == '1') {
                                return h('span', {}, '二级单位级')
                            } else if (params.row.checkLevel == '2') {
                                return h('span', {}, '班组级')
                            }
                        }
                    },
                    {
                        minWidth: 100,
                        title: '任务来源',
                        key: 'taskSource',
                        align: 'center',
                        render: (h, params) => {
                            if (params.row.taskSource == '1') {
                                return h('span', {}, '计划任务')
                            } else if (params.row.taskSource == '2') {
                                return h('span', {}, '临时任务')
                            }
                        }
                    },
                    {
                        minWidth: 100,
                        title: '责任人',
                        key: 'dutyUserName',
                        align: 'center',
                    },
                    {
                        minWidth: 100,
                        title: '任务状态',
                        key: 'taskStatus',
                        align: 'center',
                        render: (h, params) => {
                            if (params.row.taskStatus == '1') {
                                return h('span', {}, '未执行')
                            } else if (params.row.taskStatus == '2') {
                                return h('span', {}, '执行中')
                            } else if (params.row.taskStatus == '3') {
                                return h('span', {}, '已执行')
                            }
                        }
                    },
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        minWidth: 160,
                        align: 'center',
                        render: (h, params) => {
                            if (params.row.taskStatus == '1' || params.row.taskStatus == '2') {
                                return h('div', [
                                    h('A', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            fontSize: '14px',
                                        },
                                        on: {
                                            click: () => {
                                                this.toEdit(params);
                                            }
                                        }
                                    }, '执行'),
                                    h('Divider', {props: {type: 'vertical'}}, ''),
                                    h('A', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            fontSize: '14px',
                                            color: '#d0d0d0' ,
                                            pointerEvents: 'none'
                                        },
                                        on: {
                                            click: () => {
                                                // this.toEdit(params);
                                            }
                                        }
                                    }, '指派责任人'),
                                ]);
                            } else {
                                return h('div', [
                                    h('A', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            fontSize: '14px',
                                        },
                                        on: {
                                            click: () => {
                                                this.viewData(params);
                                            }
                                        }
                                    }, '详情'),
                                    h('Divider', {props: {type: 'vertical'}}, ''),
                                    h('A', {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            fontSize: '14px',
                                            color: params.row.dutyUser!=null&&params.row.dutyUser!=''&&params.row.dutyUser!=undefined?'#d0d0d0':'' ,
                                            pointerEvents: params.row.dutyUser!=null&&params.row.dutyUser!=''&&params.row.dutyUser!=undefined?'none':''
                                        },
                                        on: {
                                            click: () => {
                                                this.model2=true
                                                this.mainInstanceId=params.row.mainInstanceId
                                                this.checkedOrg = params.row.checkedOrg
                                            }
                                        }
                                    }, '指派责任人'),
                                ]);
                            }
                        }
                    }
                ],
                dataTable: [],
                buttonLoading: false,
                hasModel: false,
                checkedOrg:'',//受检单位id
                noModel: false,
                loading: false,
                tableHeight: '',
                model2:false,
                loading1:false,
                options1:[],
                dutyUser:null,
                dutyUserName:null,
                ruleCustom: {
                    dutyUser: [{
                        validator: (rule, value, callback) => {
                            if (this.dutyUser == null || this.dutyUser == undefined || this.dutyUser == '') {
                                callback('责任人不能为空')
                            } else {
                                callback()
                            }
                        },
                        required: true,
                        trigger: 'change'
                    }],
                },
                mainInstanceId:null
            }
        },
        mounted: function () {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.query();
        },
        methods: {
            submit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.buttonLoading=true
                        let url = Api.responsibleSelect
                        this.$http.get(url+'?mainInstanceId='+this.mainInstanceId+''+'&dutyUser='+this.dutyUser).then((res) => {
                            this.$Message.success('成功');
                            this.model2 = false
                            this.buttonLoading=false
                            this.query()
                        }).catch(e => {
                            this.$Message.error('请求失败');
                            this.buttonLoading=false
                        })
                    }else {
                        this.$Message.error('责任人不能为空!');
                    }
                })

            },
            remoteMethod1(query){
                if(this.dutyUser == query){
                    return ;
                }
                if (query !== '') {
                    clearTimeout(this.remoteMethod1.timer);
                    this.remoteMethod1.timer = setTimeout(()=>{
                        this.loading1 = true;
                        let data = {
                            userName: query,
                            orgId: this.checkedOrg
                        };
                        this.$http.get(Api.queryUserByUserName , {params: data}).then((res) => {
                            this.loading1 = false;
                            this.options1 = res.data.data;
                        }).catch(e => {
                            this.loading1 = false;
                        })
                    },200);
                } else {
                    this.options1 = [];
                }
            },
            closeModel() {
                console.log(1111111)
                this.hasModel = false;
                this.noModel = false;
            },
            pageChange(pageNum) {
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            pageSizeChange(pageSize) {
                this.pagedata.pageSize = pageSize;
                this.query();
            },

            toEdit(params) {
                if (params.row.modelId != null && params.row.modelId != '') {
                    this.mainTaskId = params.row.mainTaskId;
                    this.editable = true;
                    this.hasModel = true;
                    setTimeout(() => {
                        this.$refs.hasModelModal.toEdit();
                    }, 100)
                } else {
                    this.mainTaskId = params.row.mainTaskId;
                    this.editable = true;
                    this.noModel = true;
                    setTimeout(() => {
                        this.$refs.noModelModal.toEdit();
                    }, 100)
                }
            },
            viewData(params) {
                console.log(params.row.mainTaskId)
                if (params.row.modelId != null && params.row.modelId != '') {
                    this.hasModel = true;
                    this.mainTaskId = params.row.mainTaskId;
                    this.editable = false;
                    setTimeout(() => {
                        this.$refs.hasModelModal.viewData();
                    }, 100)
                } else {
                    this.noModel = true;
                    this.mainTaskId = params.row.mainTaskId;
                    this.editable = false;
                    setTimeout(() => {
                        this.$refs.noModelModal.viewData();
                    }, 100)
                }
            },
            query() {
                this.loading = true;
                let data = {
                    currentPage: this.pagedata.currentPage,
                    size: this.pagedata.pageSize,
                    userId: JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserId"],
                    checkCategory: this.$route.query.id
                }
                if (this.form1.checkTime[0] != '') {
                    let checkTime1 = new Date(this.form1.checkTime[0])
                    this.form1.checkTime1 = checkTime1.getFullYear() + '-' + (checkTime1.getMonth() + 1) + '-' + checkTime1.getDate()
                    let checkTime2 = new Date(this.form1.checkTime[1])
                    this.form1.checkTime2 = checkTime2.getFullYear() + '-' + (checkTime2.getMonth() + 1) + '-' + checkTime2.getDate()
                }
                data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

                let url = Api.getSecurityCheckTaskList;
                this.$http.get(url, {params: data}).then((res) => {
                    this.dataTable = res.data.data;
                    this.pagedata.total = res.data.totalSize;
                    this.loading = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },
            reset() {
                this.form1 = {};
                this.form1.checkTime=['','']
                this.query();
            },
            getSelectRows(rows) {
                this.selectRows = rows;
            },
            switchQuery(flag) {
                this.switchFlag = flag;
                if (!this.switchFlag) {
                    this.tableHeight = this.tableHeight + 44;
                } else {
                    this.tableHeight = this.tableHeight - 44;
                }
            },
            toSubmit() {
                let selectRows = this.selectRows;
                if (selectRows.length == 0 || selectRows.length > 1) {
                    this.$Message.info('请选择一条数据！');
                    return;
                }
                let mainTaskId = selectRows[0].mainTaskId;
                let taskCheckLineId = selectRows[0].taskCheckLineId;
                let taskCheckPointId = selectRows[0].taskCheckPointId;
                let userId = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createUserId"];
                let orgId = JSON.parse(sessionStorage('paramUserInfo').get('userInfo'))["createOrgId"];

                let formData = {
                    mainTaskId: mainTaskId,
                    taskCheckLineId: taskCheckLineId,
                    taskCheckPointId: taskCheckPointId,
                    userId: userId,
                    orgId: orgId,
                };
                if (selectRows[0].taskStatus == '3') {
                    this.$Message.warning('已执行的任务不可提交,请确认！');
                    return;
                }
                let _this = this;
                let config = {
                    title: '系统提示',
                    content: '确认提交选中数据吗?',
                    okText: '确定',
                    cancelText: '取消',
                    onOk: function () {
                        _this.$Spin.show({
                            render: (h) => {
                                return h('div', [
                                    h('Icon', {
                                        'class': 'demo-spin-icon-load',
                                        props: {
                                            type: 'ios-loading',
                                            size: 18
                                        }
                                    }),
                                    h('div', 'Loading')
                                ])
                            }
                        });
                        let url = Api.securityCheckSubmitTask;
                        this.$http.get(url, {params: formData}).then((res) => {
                            if (res.data.result == "success") {
                                _this.$Message.success('提交成功!');
                                _this.query();
                                _this.$Spin.hide();
                            } else {
                                this.$Message.error("提交失败！");
                            }

                        }).catch(e => {
                            _this.$Spin.hide();
                            _this.$Message.error('提交失败' + e);
                        })
                    },
                    onCancel: function () {
                    }
                }
                this.$Modal.confirm(config);
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
        },
    }
</script>
<style lang='css'>
    @import '../../../../index.css';
    .demo-upload-list {
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
        margin-right: 4px;
    }

    .demo-upload-list img {
        width: 100%;
        height: 100%;
    }

    .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .6);
    }

    .demo-upload-list:hover .demo-upload-list-cover {
        display: block;
    }

    .demo-upload-list-cover i {
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
